// SakuraBackground.vue
<script setup>
import { onMounted, onUnmounted, ref } from 'vue'

const sakuraContainer = ref(null)

// 创建樱花类
class Sakura {
  constructor(container) {
    this.container = container
    this.init()
  }

  init() {
    // 创建樱花元素
    this.el = document.createElement('div')
    this.el.className = 'sakura'
    this.el.style.left = Math.random() * window.innerWidth + 'px'
    this.el.style.top = '-50px'
    this.container.appendChild(this.el)

    // 初始化属性
    this.x = parseFloat(this.el.style.left)
    this.y = parseFloat(this.el.style.top)
    this.scale = Math.random() * 0.4 + 0.6
    this.rotation = Math.random() * 360
    this.speedX = Math.random() * 2 - 1
    this.speedY = Math.random() * 2 + 1
    this.rotationSpeed = (Math.random() - 0.5) * 2

    this.update()
  }

  update() {
    if (!this.container) return

    // 更新位置和旋转
    this.y += this.speedY
    this.x += this.speedX + Math.sin(this.y / 50) * 0.5
    this.rotation += this.rotationSpeed

    // 应用变换
    this.el.style.transform = `translate(${this.x}px, ${this.y}px) rotate(${this.rotation}deg) scale(${this.scale})`

    // 检查是否超出界限，如果是则重置
    if (this.y > window.innerHeight || this.x < -50 || this.x > window.innerWidth + 50) {
      this.container.removeChild(this.el)
      this.init()
    } else {
      requestAnimationFrame(this.update.bind(this))
    }
  }

  destroy() {
    if (this.el && this.el.parentNode) {
      this.el.parentNode.removeChild(this.el)
    }
  }
}

// 储存所有樱花实例
const sakuras = ref([])

// 创建多个樱花
const createSakuras = () => {
  const count = 30 // 樱花数量
  for (let i = 0; i < count; i++) {
    setTimeout(() => {
      if (sakuraContainer.value) {
        sakuras.value.push(new Sakura(sakuraContainer.value))
      }
    }, i * 300) // 间隔创建，使效果更自然
  }
}

// 生命周期钩子
onMounted(() => {
  createSakuras()
})

onUnmounted(() => {
  sakuras.value.forEach(sakura => sakura.destroy())
  sakuras.value = []
})
</script>

<template>
  <div ref="sakuraContainer" class="sakura-container">
    <slot></slot>
  </div>
</template>

<style scoped>
.sakura-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.sakura {
  position: absolute;
  width: 20px;
  height: 20px;
  background: #ffd7e6;
  border-radius: 150% 0 150% 0;
  display: inline-block;
  animation: floatAnimation 4s ease-in-out infinite;
  filter: drop-shadow(0 0 2px rgba(255, 215, 230, 0.9));
}

.sakura::after {
  content: '';
  position: absolute;
  top: -14%;
  left: -10%;
  display: block;
  width: 100%;
  height: 100%;
  background: #ffd7e6;
  border-radius: 150% 0 150% 0;
  transform: rotate(15deg);
}

@keyframes floatAnimation {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}
</style>